package com.hmall.gateway.filters;

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;

    private final JwtTool jwtTool;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数 request
        ServerHttpRequest request = exchange.getRequest();

        // 2.判断请求路径是否是配置类中需要跳过的
        if (isIncludePath(request.getPath())) {
            // 放行
            return chain.filter(exchange);
        }
        // 3.获取请求头重的token
        String token = request.getHeaders().getFirst("authorization");
        // 4.如果token不为空就校验token
        Long userId;
        // 校验并解析token
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            // 如果无效，拦截，给一个未登录的状态码401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
           return response.setComplete();
        }


        // 将获取的用户信息保存到请求头中
//        System.out.println("userId = " + userId);
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("user-info", userId.toString()))
                .build();
        // 6.放行

        return chain.filter(swe);
    }

    // 判断请求路径是否是配置类中需要跳过的
    private boolean isIncludePath(RequestPath path) {
        List<String> excludePaths = authProperties.getExcludePaths();
        for (String excludePath : excludePaths) {
            if (antPathMatcher.match(excludePath, path.value())) {
                // 如果是需要跳过的路径则返回true
                return true;
            }
        }
        // 如果不需要跳过则返回false
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
